package demo.java.lang.instrument;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

public class UnsafeDemo {

    private static Logger logger = LoggerFactory.getLogger(UnsafeDemo.class);

    /**
     * 结合反射来计算对象的大小。下面说一下通过sun.misc.Unsafe对象的objectFieldOffset(field)等方法结合反射来计算对象的大小。基本的思路如下:
     * <li>1. 通过反射获得一个类的Field
     * <li>2. 通过Unsafe的objectFieldOffset()获得每个Field的offSet
     * <li>3. 对Field按照offset排序，取得最大的offset，然后加上这个field的长度，再加上Padding对齐
     * <p>
     * <br>
     * 上面三步就可以获得一个对象的Shallow size。可以进一步通过递归去计算所引用对象的大小，从而可以计算出一个对象所占用的实际大小。
     */
    @Test
    public void unsafe() {
        final ClassIntrospector ci = new ClassIntrospector();
    }

    /**
     * Unsafe有一个allocateInstance(Class)方法，这个方法只需要传入一个类型就可以创建Java对象了。 可以解决这个由于有参构造函数引起的创建Java对象的问题。
     * allocateInstance()方法值做了分配内存空间和返回内存地址，没有做第三步调用构造函数。
     * 所以Unsafe.allocateInstance()方法创建的对象都是只有初始值，没有默认值也没有构造函数设置的值，因为它完全没有使用new机制，直接操作内存创建了对象。
     */
    @Test
    public void newObject() {
    }


}

class ObjectA {
    String str; // 4
    int i1; // 4
    byte b1; // 1
    byte b2; // 1
    int i2; // 4
    Object obj; // 4
    byte b3; // 1
}

/**
 * This class could be used for any object contents/memory layout printing.
 */
class ClassIntrospector {


    /**
     * Sizes of all primitive values
     */
    private static final Map<Class, Integer> primitiveSizes;

    static {
        primitiveSizes = new HashMap<Class, Integer>(10);
        primitiveSizes.put(byte.class, 1);
        primitiveSizes.put(char.class, 2);
        primitiveSizes.put(int.class, 4);
        primitiveSizes.put(long.class, 8);
        primitiveSizes.put(float.class, 4);
        primitiveSizes.put(double.class, 8);
        primitiveSizes.put(boolean.class, 1);
    }


    // we need to keep track of already visited objects in order to support
    // cycles in the object graphs
    private IdentityHashMap<Object, Boolean> m_visited = new IdentityHashMap<Object, Boolean>(100);


    // get all fields for this class, including all superclasses fields
    private static List<Field> getAllFields(final Class type) {
        if (type.isPrimitive())
            return Collections.emptyList();
        Class cur = type;
        final List<Field> res = new ArrayList<Field>(10);
        while (true) {
            Collections.addAll(res, cur.getDeclaredFields());
            if (cur == Object.class)
                break;
            cur = cur.getSuperclass();
        }
        return res;
    }

    // check if it is an array of objects. I suspect there must be a more
    // API-friendly way to make this check.
    private static boolean isObjectArray(final Class type) {
        if (!type.isArray())
            return false;
        if (type == byte[].class || type == boolean[].class || type == char[].class || type == short[].class
                || type == int[].class || type == long[].class || type == float[].class || type == double[].class)
            return false;
        return true;
    }

    // advanced toString logic
    private static String getContents(final Object val, final Class type) {
        if (val == null)
            return "null";
        if (type.isArray()) {
            if (type == byte[].class)
                return Arrays.toString((byte[]) val);
            else if (type == boolean[].class)
                return Arrays.toString((boolean[]) val);
            else if (type == char[].class)
                return Arrays.toString((char[]) val);
            else if (type == short[].class)
                return Arrays.toString((short[]) val);
            else if (type == int[].class)
                return Arrays.toString((int[]) val);
            else if (type == long[].class)
                return Arrays.toString((long[]) val);
            else if (type == float[].class)
                return Arrays.toString((float[]) val);
            else if (type == double[].class)
                return Arrays.toString((double[]) val);
            else
                return Arrays.toString((Object[]) val);
        }
        return val.toString();
    }
}

/**
 * This class contains object info generated by ClassIntrospector tool
 */
class ObjectInfo {
    /**
     * Field name
     */
    public final String name;
    /**
     * Field type name
     */
    public final String type;
    /**
     * Field data formatted as string
     */
    public final String contents;
    /**
     * Field offset from the start of parent object
     */
    public final int offset;
    /**
     * Memory occupied by this field
     */
    public final int length;
    /**
     * Offset of the first cell in the array
     */
    public final int arrayBase;
    /**
     * Size of a cell in the array
     */
    public final int arrayElementSize;
    /**
     * Memory occupied by underlying array (shallow), if this is array type
     */
    public final int arraySize;
    /**
     * This object fields
     */
    public final List<ObjectInfo> children;

    public ObjectInfo(String name, String type, String contents, int offset, int length, int arraySize, int arrayBase,
                      int arrayElementSize) {
        this.name = name;
        this.type = type;
        this.contents = contents;
        this.offset = offset;
        this.length = length;
        this.arraySize = arraySize;
        this.arrayBase = arrayBase;
        this.arrayElementSize = arrayElementSize;
        children = new ArrayList<ObjectInfo>(1);
    }

    public void addChild(final ObjectInfo info) {
        if (info != null) {
            children.add(info);
        }
    }

    /**
     * Get the full amount of memory occupied by a given object. This value may be slightly less than an actual value
     * because we don't worry about memory alignment - possible padding after the last object field.
     * <p>
     * The result is equal to the last field offset + last field length + all array sizes + all child objects deep sizes
     *
     * @return Deep object size
     */
    public long getDeepSize() {
        // return length + arraySize + getUnderlyingSize( arraySize != 0 );
        return addPaddingSize(arraySize + getUnderlyingSize(arraySize != 0));
    }

    long size = 0;

    private long getUnderlyingSize(final boolean isArray) {
        // long size = 0;
        for (final ObjectInfo child : children)
            size += child.arraySize + child.getUnderlyingSize(child.arraySize != 0);
        if (!isArray && !children.isEmpty()) {
            int tempSize = children.get(children.size() - 1).offset + children.get(children.size() - 1).length;
            size += addPaddingSize(tempSize);
        }

        return size;
    }

    private static final class OffsetComparator implements Comparator<ObjectInfo> {
        @Override
        public int compare(final ObjectInfo o1, final ObjectInfo o2) {
            return o1.offset - o2.offset; // safe because offsets are small non-negative numbers
        }
    }

    // sort all children by their offset
    public void sort() {
        Collections.sort(children, new OffsetComparator());
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        toStringHelper(sb, 0);
        return sb.toString();
    }

    private void toStringHelper(final StringBuilder sb, final int depth) {
        depth(sb, depth).append("name=").append(name).append(", type=").append(type).append(", contents=")
                .append(contents).append(", offset=").append(offset).append(", length=").append(length);
        if (arraySize > 0) {
            sb.append(", arrayBase=").append(arrayBase);
            sb.append(", arrayElemSize=").append(arrayElementSize);
            sb.append(", arraySize=").append(arraySize);
        }
        for (final ObjectInfo child : children) {
            sb.append('\n');
            child.toStringHelper(sb, depth + 1);
        }
    }

    private StringBuilder depth(final StringBuilder sb, final int depth) {
        for (int i = 0; i < depth; ++i)
            sb.append("\t");
        return sb;
    }

    private long addPaddingSize(long size) {
        if (size % 8 != 0) {
            return (size / 8 + 1) * 8;
        }
        return size;
    }

}
